<template>
  <div class="main">
     <p class="main_text">物流结算</p>
      <!-- 搜索 -->
      <div class="g-search">
        <!-- 时间选择区域 -->
        <div class="demo-date-picker">
          <div class="block">
            <span class="demonstration">付款时间:</span>
            <el-date-picker v-model="searchValue.startAt" type="date" placeholder="开始时间" @change="startTime"
              :clearable="false" :default-time="defaultTime(0, 0, 0)" />
            <span class="demonstration" style="
                display: inline-block;
                font-size: 12px;
                color: #898989;
                margin: 20px;
              ">至</span>
            <el-date-picker v-model="searchValue.endAt" type="date" placeholder="结束时间" @change="endTime"
              :clearable="false" :default-time="defaultTime(23, 59, 59)" />
            &emsp;
            <span class="demonstration">物流公司:</span>
            <el-select v-model="searchValue.company" style="width: 250px">
              <el-option v-for="item in companyListData" :key="item.name" :label="item.name" :value="item.code" />
            </el-select>
            <span class="demonstration" style="margin-left: 15px;">发票状态:</span>
            <el-select v-model="searchValue.status" style="width: 250px">
              <el-option label="未收到" value="0" />
              <el-option label="已收到" value="1" />
            </el-select>
          </div>
        </div>
        <!-- 底部按钮区域 -->
        <div class="bottom_btn">
          <el-button class="solid" @click="search">查询</el-button>
          <el-button class="hollow" @click="reset">重置</el-button>
        </div>
      </div>
    <!-- ############################################## 数据表格 ############################################## -->
    <div class="cyr-flex">
      <div class="mb20">
        <el-button type="primary" v-if="roleList.write" @click="handleBatchConfirm">批量确认发票</el-button>
        <el-button v-if="roleList.write" @click="handleExportExcel">导出明细</el-button>
      </div>
      <div class="cyr-flex-box">
      <el-table :data="tableData"   @selection-change="handleSelectionChange"
        :show-overflow-tooltip="true"  v-adaptive border>
        <el-table-column type="selection" width="50" :selectable="selectable" />
        <el-table-column label="结算时间" prop="settleMonth">
          <template #default="scope">
            {{ moment(scope.row.startAt).format('YYYY-MM-DD') }}/{{ moment(scope.row.endAt).format('YYYY-MM-DD') }}
          </template>
        </el-table-column>
        <el-table-column label="订单数量" prop="settileCount"></el-table-column>
        <el-table-column label="物流结算合计" prop="settileAmount"></el-table-column>
        <el-table-column label="付款人" prop="company">
        </el-table-column>
        <el-table-column label="是否确认">
          <template #default="scope">
            {{ scope.row.invoiceStatus ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" prop="updateAt"></el-table-column>
        <el-table-column label="操作" width="120" :show-overflow-tooltip="false" fixed="right">
          <template #default="props">
            <el-button size="small" link type="primary" v-if="roleList.read" @click="handleView">查看</el-button>
            <el-button size="small" link type="primary" v-if="roleList.write && !props.row.invoiceStatus"
              @click="handleConfirm(props.row.id)">确认发票</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <smartPager v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
        @change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import useAuthorize from "@/hooks/authorize";
import moment from "moment";
import { ElMessage } from "element-plus";
import { RequesLogistics, RequestLogisticsCompany, RequestConfirmInvoice } from '@/api/path/index';
import { formatJson, formatTimeHan } from '@/utils';
import { exportJson2Excel } from '@/utils/excel';
let roleList = useAuthorize();
//响应数据类型
interface ResultObj {
  count: number;
  list: any[]; // 这里可以根据实际情况定义更具体的类型
}
interface Response {
  code: number;
  success: boolean;
  msg: string;
  resultObj: ResultObj;
}
const page = ref(1);
const currentPage = ref<number>(1)
const pageSize = ref<number>(10)
//查询条件
const searchValue = ref({
  startAt: "",
  endAt: "",
  page: currentPage.value,
  rows: pageSize.value,
  company: '',
  status: ''
});

const defaultTime = (h: number, m: number, s: number) => {
  let now = new Date();
  now.setHours(h);
  now.setMinutes(m);
  now.setSeconds(s);
  return now;
}
/**
* 点击重置
*/
const reset = () => {
  searchValue.value = {
    startAt: "",
    endAt: "",
    page: 1,
    rows: 10,
    company: '',
    status: ''
  };
  currentPage.value = 1;
  initData(searchValue.value);
};
// 开始时间
const startTime = () => {
  searchValue.value.startAt = moment(searchValue.value.startAt).format("YYYY-MM-DD HH:mm:ss");
};
// 结束时间
const endTime = () => {
  searchValue.value.endAt = moment(searchValue.value.endAt).format("YYYY-MM-DD HH:mm:ss");
};
/**
* 搜索点击事件
*/
const search = async () => {
  //时间是否存在
  if (searchValue.value.startAt !== "" && searchValue.value.endAt !== "") {
    if (moment(searchValue.value.startAt).diff(moment(searchValue.value.endAt)) >= 0) {
      ElMessage.error("开始时间不能晚于结束时间");
    } else {
      page.value = 1;
      //请求数据
      initData(searchValue.value);
    }
  } else {
    initData(searchValue.value);
  }
};
/**
 * 导出Excel
 */
const handleExportExcel = () => {
  const tHeader = ['编号', '物流公司', '结算时间', '订单数量', '物流计算合计', '是否确认付款', '更新时间']
  const filterVal = ['id', 'company', 'settleMonth', 'settileCount', 'settileAmount', 'invoiceStatus', 'updateAt']
  const list = tableData.value.map((item, index) => {
    return {
      ...item,
      id: index,
      invoiceStatus: item.invoiceStatus ? '是' : '否'
    }
  })
  const data = formatJson(filterVal, list)
  exportJson2Excel(tHeader, data, `${formatTimeHan(new Date())}物流结算`, undefined, undefined,)
}
// 表格数据
const tableData = ref<any[]>([])
const total = ref(0)

//物流公司列表
const companyListData = ref();
function companyList() {
  RequestLogisticsCompany().then((res: Response) => {
    companyListData.value = res.resultObj;
  });
}
companyList();

//确认发票
function confirmInvoice(ids: number[]) {
  RequestConfirmInvoice(ids).then((res: Response) => {
    if (res.resultObj) {
      ElMessage.success(res.msg)
      initData(searchValue.value);
    }
  });
}
//确认发票事件
const handleConfirm = (id: number) => {
  confirmInvoice([id])
}
//批量确认发票
let ids: Array<number> = []
const handleSelectionChange = (item: any) => {
  ids = item.map((item: any) => item.id)
}
const handleBatchConfirm = () => {
  confirmInvoice(ids)
}
//查看事件
const handleView = () => {

}
//禁止选中
const selectable = (item: any) => item.invoiceStatus === 0
// 初始化数据
function initData(search: any) {
  searchValue.value.rows = pageSize.value
  searchValue.value.page = currentPage.value
  RequesLogistics(search).then((res: Response) => {
    tableData.value = res.resultObj.list
    total.value = res.resultObj.count
  })
}
initData(searchValue.value);
//分页查询事件
const handleCurrentChange = (val: number) => {
  searchValue.value.page = val
  initData(searchValue.value);
}
</script>
<style lang="scss" scoped>
.main {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .content {
    width: 100%;
    background-color: #fff;
  }
}

.order {
  .box {
    width: 96%;
    padding: 20px;
    background: #ffffff;
    margin: 20px auto;
    display: flex;
    flex-wrap: wrap;

    .title {
      width: 100%;
      display: flex;

      .right {
        flex: 1;

        .el-steps {
          padding: 0 0 20px 0;
          border-bottom: 1px solid #b9b9b9;
        }

        .text {
          width: 100%;
          margin: 10px 0 25px 0;

          .shop {
            width: 100%;
            height: 30px;
            font-size: 18px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            color: #3d3d3d;
            font-weight: bold;
            margin-top: 20px;
          }

          .time {
            display: inline-block;
            padding: 5px;
            background: #f5f9ff;
            color: #409eff;
          }

          .text1 {
            font-size: 14px;
            color: #ababab;
          }
        }
      }
    }

    .mes {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;

      .info {
        width: 195px;
        font-size: 14px;
        color: #797979;
        margin-top: 15px;
      }

      .addremark {
        display: inline-block;
        color: #116cf8;
        margin-left: 10px;
        font-size: 12px;
      }
    }

    .user_play {
      width: 50%;
      font-size: 14px;

      .box1 {
        width: 3px;
        height: 15px;
        border: 0;
        background: #116cf8;
        margin-right: 10px;
      }

      .name {
        font-weight: bold;
        font-size: 15px;
      }

      .title {
        display: flex;
        border: 0;
        align-items: center;
        font-size: 15px;
        margin-bottom: 15px;

        .box1_other {
          background: #fff;
        }
      }

      .row {
        margin-top: 5px;

        .name1 {
          color: #b8b8b8;
        }
      }
    }

    .head_title {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      font-size: 15px;
      font-weight: bold;

      .box1 {
        width: 3px;
        height: 20px;
        background: #116cf8;
        margin-right: 10px;
      }
    }

    .logistics {
      margin-top: 20px;
    }

    .deposit {
      background: #fff;
      border: 0px;
      color: #409eff;
    }
  }


  .fristbox {
    margin-top: 0px;
  }
}
</style>